package com.ytjj.qmyx.admin.service.channelProductService.impl;


import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.utils.HttpClientUtil;
import com.ytjj.qmyx.admin.config.SupplyApiConfig;
import com.ytjj.qmyx.admin.dao.ProductDao;
import com.ytjj.qmyx.admin.dao.channel.FreightTemplateDao;
import com.ytjj.qmyx.admin.model.request.FreigRequest;
import com.ytjj.qmyx.admin.model.request.YxAssignFreight;
import com.ytjj.qmyx.admin.model.request.YxAstrictRegion;
import com.ytjj.qmyx.admin.model.request.YxFreightTemplate;
import com.ytjj.qmyx.admin.model.response.ProductDataResponse;
import com.ytjj.qmyx.admin.model.response.goods.YxAssignFreightResponse;
import com.ytjj.qmyx.admin.service.channelProductService.FreightTemplateService;
import com.ytjj.qmyx.admin.model.response.goods.FreightTemplateResponse;
import com.ytjj.qmyx.mall.model.Product;
import com.ytjj.qmyx.mall.model.YxAstrictRegionResponse;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.map.LinkedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
@RefreshScope
public class FreightTemplateServiceImpl implements FreightTemplateService {

    @Autowired
    private FreightTemplateDao freightTemplateDao;

    @Autowired
    private ProductDao productDao;

    @Resource
    private SupplyApiConfig supplyApiConfig;

    @Value("${h5.default.template.id:10001}")
    private Integer h5DefaultTemplateId;
    @Value("${app.default.template.id:10002}")
    private Integer appDefaultTemplateId;


    @Override
    public CommonPage selectFreightTemplatePage(FreigRequest freigRequest) {
        PageHelper.startPage(freigRequest.getPageNum(), freigRequest.getPageSize());
        List<FreightTemplateResponse> list =freightTemplateDao.selectFreightTemplatePage(freigRequest.getTemplateName(),freigRequest.getPlatformData(),freigRequest.getFreightType());
        //模板id集合
        List<Integer> templateIdList = list.stream().map(FreightTemplateResponse::getId).collect(Collectors.toList());
        List<YxAssignFreightResponse> yxAssignFreightResponses = freightTemplateDao.queryYxAssignFreightByFreightId(null, templateIdList);
        list.forEach(item -> {
            Integer id = item.getId();
            List<YxAssignFreightResponse> yxAssignFreightList = yxAssignFreightResponses.stream().filter(yxAssignFreightResponse -> id.equals(yxAssignFreightResponse.getFreightId())).collect(Collectors.toList());
//            List<YxAssignFreightResponse> yxAssignFreightList = freightTemplateDao.queryYxAssignFreightByFreightId(id);
            List<ProductDataResponse> productDataResponses = freightTemplateDao.queryProductDataResponse(id);
            item.setProductDataResponses(productDataResponses.size());
            item.setAssignFreightList(yxAssignFreightList);
        });
        return CommonPage.restPage(list);
    }

    @Override
    public Integer insertFreightTemplate(YxFreightTemplate yxFreightTemplate) {
//        Admin admin = UserUtil.getAdmin();
//        Integer bankerId = admin.getBankerId();
//        if(freightTemplateDao.selectFreightTemplates(yxFreightTemplate.getTemplateName(),bankerId)!=0){
//            return 2;
//        }
//        if (null == yxFreightTemplate.getBankerId()){
//            // 获取当前的登录人的id
//            yxFreightTemplate.setBankerId(bankerId);
//        }
        freightTemplateDao.insertFreightTemplate(yxFreightTemplate);
        if(yxFreightTemplate.getAssignFreightList() != null && yxFreightTemplate.getAssignFreightList().size()!=0){
            freightTemplateDao.insertAssignFreightList(yxFreightTemplate.getAssignFreightList(), yxFreightTemplate.getId());
        }
        if(yxFreightTemplate.getAstrictRegion()!=null && StringUtils.isNotEmpty(yxFreightTemplate.getAstrictRegion().getRegion())){
            freightTemplateDao.insertAstrictRegion(yxFreightTemplate.getAstrictRegion(),yxFreightTemplate.getId());
        }
        return 1;
    }

    @Override
    public Integer deleteFreightTemplate(Integer id) {
        freightTemplateDao.deleteFreightTemplate(id);
        freightTemplateDao.deleteAssignFreightList(id);
        freightTemplateDao.deleteAstrictRegionList(id);
        return 1;
    }

    @Override
    public Integer deleteAssignFreight(Integer id) {
        return freightTemplateDao.deleteAssignFreight(id);
    }

    @Override
    public Integer deleteAstrictRegion(Integer id) {
        return freightTemplateDao.deleteAstrictRegion(id);
    }

    @Override
    public Integer updateAssignFreight(YxAssignFreight yxAssignFreight) {
        return freightTemplateDao.updateAssignFreight(yxAssignFreight);
    }

    @Override
    public Integer updateAstrictRegion(YxAstrictRegion yxAstrictRegion) {
        return freightTemplateDao.updateAstrictRegion(yxAstrictRegion);
    }

    @Override
    public Integer updateFreightTemplate(YxFreightTemplate yxFreightTemplate) {
        freightTemplateDao.updateFreightTemplate(yxFreightTemplate);
        if(yxFreightTemplate.getFreightWay()==0 && yxFreightTemplate.getAssignFreightList().size()!=0) {
            freightTemplateDao.deleteAssignFreightList(yxFreightTemplate.getId());
            freightTemplateDao.insertAssignFreightList(yxFreightTemplate.getAssignFreightList(), yxFreightTemplate.getId());
        }
        if(yxFreightTemplate.getAstrictRegion()==null){
            freightTemplateDao.deleteAstrictRegionList(yxFreightTemplate.getId());
        }else if(yxFreightTemplate.getAstrictRegion().getId()!=null){
            freightTemplateDao.updateAstrictRegion(yxFreightTemplate.getAstrictRegion());
        }else{
            freightTemplateDao.insertAstrictRegion(yxFreightTemplate.getAstrictRegion(),yxFreightTemplate.getId());
        }
        return 1;
    }

    @Override
    public Integer updateDefaults(Integer id,String platformData) {
        if(id == 0 ) {
            if(StringUtils.isNotEmpty(platformData)) {
                freightTemplateDao.updateDefaults(platformData);
                Integer templateId = "app".equals(platformData)? appDefaultTemplateId:h5DefaultTemplateId;
                freightTemplateDao.updateDefault(templateId);
                return 1;
            }
        }
        freightTemplateDao.updateDefaults(platformData);
        freightTemplateDao.updateDefault(id);
        return 1;
    }



    @Override
    public FreightTemplateResponse selectFreightTemplateResponse(Integer id) {
        FreightTemplateResponse freightTemplateResponse = freightTemplateDao.selectFreightTemplateResponse(id);
        if(freightTemplateResponse != null ){
            freightTemplateResponse.setAssignFreightList(freightTemplateDao.queryYxAssignFreightResponseByFreightId(id));
        }
        return freightTemplateResponse;
    }

    @Override
    public FreightTemplateResponse selectBySupplyTemplateIdAndPlatformData(Integer supplyTemplateId, String platformData,Integer freightType) {
        FreightTemplateResponse freightTemplateResponse = freightTemplateDao.selectBySupplyTemplateIdAndPlatformData(supplyTemplateId,platformData,freightType);
        if(freightTemplateResponse == null) {
            return null;
        }
        freightTemplateResponse.setAssignFreightList(freightTemplateDao.queryYxAssignFreightResponseByFreightId(freightTemplateResponse.getId()));
        return freightTemplateResponse;
    }

    @Override
    public FreightTemplateResponse selectYxFreightTemplateByProductId(Integer id) {
        Product product = productDao.getProductById(id);
        if(product !=null) {
            return selectFreightTemplateResponse(product.getFreightId());
        }
        return  null ;
    }

    @Override
    public FreightTemplateResponse selectChainFreightTemplateByProductId(Integer productId) {
        Product product = productDao.getProductById(productId);
        Map<String, String> map = new LinkedMap();
        map.put("id", String.valueOf(product.getBankerProductId()));
        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/product/findFreightTemplateResponse", map, supplyApiConfig.getHeadsMap());
        if (null == resultJson) {
            return null;
        }
        return JSONObject.parseObject(resultJson, FreightTemplateResponse.class);
    }

    @Override
    public FreightTemplateResponse selectDefaultFreightTemplate(String platformData) {
        return selectFreightTemplateResponse("app".equals(platformData)? appDefaultTemplateId :h5DefaultTemplateId);
    }


    @Override
    public void syncYxFreightTemplate(){
//        Map<String, String> map = new LinkedMap();
//        map.put("id", "");
//        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/product/getFreightTemplateProduct", map, supplyApiConfig.getHeadsMap());
//        List<Integer> ids = JSONObject.parseObject(resultJson, List.class);
        List<Product> products = productDao.selectUpAndNotHaveTemplate();
        if(CollectionUtils.isNotEmpty(products)) {
            products.stream().forEach( product -> {
                YxFreightTemplate freightTemplate = getFreightTemplateResponse(product.getId());
                if(freightTemplate != null ){
                    FreightTemplateResponse oldFreightTemplate = selectBySupplyTemplateIdAndPlatformData(freightTemplate.getId(), product.getPlatformData(),2);
                    if(oldFreightTemplate == null) {
                        freightTemplate.setFreightType(2);
                        insertFreightTemplate(freightTemplate);
                        product.setFreightId(freightTemplate.getId());
                    } else {
                        product.setFreightId(oldFreightTemplate.getId());
                    }
                }else{
                    product.setFreightId("app".equals(product.getPlatformData())? appDefaultTemplateId :h5DefaultTemplateId);
                }
//                productDao.updateByEntity(product);
                productDao.updateProductFreightId(product.getId(),product.getFreightId());
            });
        }

    }

    public YxFreightTemplate getFreightTemplateResponse(Integer productId) {
        Product product = productDao.getProductById(productId);
        Map<String, String> map = new LinkedMap();
        map.put("id", String.valueOf(product.getBankerProductId()));
        String resultJson = HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/product/findFreightTemplateResponse", map, supplyApiConfig.getHeadsMap());
        if (null == resultJson) {
            return null;
        }
        if(StringUtils.isNotEmpty(resultJson)) {
            YxFreightTemplate data = JSONObject.parseObject(resultJson, YxFreightTemplate.class);
            data.setSupplyTemplateId(data.getId());
            data.setPlatformData(product.getPlatformData());
            return data;
        }

        return null;
    }

    @Override
    public void syncYxAstricRegion() {
        List<YxAstrictRegionResponse> yxAstrictRegions = freightTemplateDao.queryRegionList();
        if (CollectionUtils.isNotEmpty(yxAstrictRegions)) {
            //selectYxFreightTemplate
            yxAstrictRegions.stream().forEach(yxAstrictRegion -> {
                Map<String,String> map = new HashMap<>();
                map.put("id",String.valueOf(yxAstrictRegion.getSupplyTemplateId()));
                String templateJson= HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/freightTemplate/selectYxFreightTemplate",
                        map, supplyApiConfig.getHeadsMap());
                if (StringUtils.isNotBlank(templateJson)) {
                    JSONObject templateParse = JSON.parseObject(templateJson);
                    YxFreightTemplate template  = JSONUtil.toBean(templateParse.getString("data"), YxFreightTemplate.class);
                    if(null!=template.getAstrictRegion()) {
                        freightTemplateDao.updateYxAstrictRegionId(yxAstrictRegion.getId(),template.getAstrictRegion().getRegionId());
                    }
                }
            });

        }
    }
}